package org.example.admin.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.admin.annotation.OperationLog;
import org.example.admin.dto.TableUser;
import org.example.admin.exception.BizException;
import org.example.admin.exception.ControllerException;
import org.example.admin.service.UserService;
import org.example.admin.service.UserSystemService;
import org.example.admin.utils.ConditionWithQuery;
import org.example.admin.utils.DateUtils;
import org.example.entity.User;
import org.example.entity.UserSystem;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台用户管理
 */
@RestController
@RequestMapping("/system")
public class UserSystemController {

    @Resource
    private UserSystemService userSystemService;

    @Resource
    private UserService userService;


    @RequestMapping("/table")
    public String userSystemTable(UserSystem userSystem ){
        List<UserSystem> list = userSystemService.list(new QueryWrapper<>(userSystem));
        return JSON.toJSONString(new TableUser<>(list,list.size()));
    }


    @RequestMapping("/register")
    public boolean userSystemRegister(String userName,String password){
        if (!"".equals(userName)&&!"".equals(password)&&password!=null){
            return userSystemService.save(new UserSystem(userName,password));
        }
        return false;
    }

    @RequestMapping("/checkRep")
    public boolean checkRep(String userName){
        UserSystem one = userSystemService.getOne(new QueryWrapper<>(new UserSystem(userName)));
        return one != null;
    }


    @RequestMapping("/delete")
    public boolean delete(int userId){
        return userSystemService.removeById(userId);
    }

    @RequestMapping("/showPass")
    public UserSystem showPass(int userId){
        return userSystemService.getById(userId);
    }

    /**
     * 修改管理员密码
     * @param id
     * @param newPassword
     * @return
     */
    @RequestMapping("/updatePass")
    public boolean updatePass(int id,String newPassword){
        return userSystemService.updateById(new UserSystem(id,newPassword));
    }

    @RequestMapping("/logOut")
    public void logOut(HttpServletRequest req, HttpServletResponse rep) throws IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("userSession");
        rep.sendRedirect("/admin/login.jsp");
    }

    /**
     * Excel导出
     * @param response
     */
    @OperationLog(value = "导出Excel",requireParamInfo = true)
    @RequestMapping("/download")
    public void downloadExcel(HttpServletResponse response,HttpServletRequest req) {
        ConditionWithQuery query = new ConditionWithQuery();
        QueryWrapper<User> queryWrapper = query.withQuery(req);
        List<User> list = userService.list(queryWrapper);
        try {
            //根据时间生成文件名  20200630164834.xls
            String fileName = DateUtils.transferDateToStr(new Date(), DateUtils.DATE_KEY_STR) + ".xls";
            String fullPath = userSystemService.generateExcel(fileName,list);

            fileName = URLEncoder.encode(fileName, "utf-8");

            response.setHeader("content-disposition", "attachment;filename=" + fileName);

            FileCopyUtils.copy(new FileInputStream(fullPath), response.getOutputStream());
        } catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }
    }


    /**
     * Excel导入
     * @param userExcel
     * @return
     */
    @OperationLog(value = "上传Excel",requireParamInfo = true)
    @PostMapping("/uploadExcel")
    public Object uploadExcel(MultipartFile userExcel) {
        Map<String, Object> map = new HashMap<>();
        try {
            //获取输入流
            InputStream is = userExcel.getInputStream();
            userSystemService.parseExcelAndInsertData(is);
            map.put("code", 1);
            map.put("msg", "success");
        } catch (BizException bizException) {
            throw bizException;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ControllerException("控制层上传Excel异常: " + ex.getMessage());
        }
        return map;
    }

}
